package pers.liyan.shi.springclouddistributedlocker.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pers.liyan.shi.springclouddistributedlocker.redis.RedisLocker;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * redis 分布式锁测试
 * @author ShiLY
 * @version 1.0
 * @date 2020/2/23 15:45
 */
@Slf4j
@Component
public class RedisLockerTest {

    private final static String LOCKER_KEY = "RedisLocker";

    private final RedisLocker redisLocker;

    private final Environment environment;

    public RedisLockerTest(RedisLocker redisLocker, Environment environment) {
        this.redisLocker = redisLocker;
        this.environment = environment;
    }

    @Scheduled(cron = "0/20 * * * * ? ")
    public void execute() {
        try {
            String lockerValue = Thread.currentThread().getId() + "_" + UUID.randomUUID().toString();
            boolean acquire = redisLocker.acquire(LOCKER_KEY, lockerValue, 10, TimeUnit.SECONDS);
            if (acquire) {
                log.info("execute task, env={}", Arrays.toString(environment.getActiveProfiles()));
                Thread.sleep(5000);
                redisLocker.release(LOCKER_KEY, lockerValue);
            }
        } catch (Exception e) {
            log.error("schedule task error", e);
        }

    }

}
